import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:smart_shop/components/shop_search_bar.dart';
import 'package:smart_shop/pages/home/components/home_banner.dart';
import 'package:smart_shop/pages/home/components/home_nav.dart';
import 'package:smart_shop/pages/home/components/home_shop_list.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 3.1 保存首页数据(总)
  Map resData = {};
  // 3.2 保存首页数据(轮播图)
  List bannerList = [];
  //3.3 保存首页数据(导航)
  List navList = [];
  //3.4 保存首页数据(广告)
  List adList = [];
  //3.5 保存首页数据(商品列表)
  List goodsList = [];
  @override
  void initState() {
    // 生命周期组件
    getData();
    super.initState();
  }

  getData() async {
    Dio dio = Dio();
    Response res = await dio
        .get('http://smart-shop.itheima.net/index.php?s=/api/page/detail');
    // 3. 保存数据 + 更新视图
    setState(() {
      // 3.1 保存首页数据(总)
      // print(res);
      resData = res.data['data']['pageData'];
      // 3.2 保存轮播图数据
      bannerList = resData['items'][1]['data'];
      // print(bannerList);
      navList = resData['items'][3]['data'];
      // print(navList);
      adList = resData['items'][4]['data'];
      // print(adList);
      goodsList = resData['items'][6]['data'];
      // print(goodsList);
    });
    // print(bannerList);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '智慧商城',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: Colors.red,
      ),
      body: ListView(
        children: [
          const ShopSearchBar(),
          HomeBanner(bannerList: bannerList),
          HomeNav(navList: navList),
          Container(
            child: Image.network(adList[0]['imgUrl']),
          ),
          // 富文本-猜你喜欢
          Padding(
            padding: const EdgeInsets.only(top: 5, bottom: 5),
            child: Container(
              alignment: Alignment.center,
              child: const Text('—— 猜你喜欢 ——'),
            ),
          ),
          HomeShopList(goodsList: goodsList)
        ],
      ),
    );
  }
}
